package zqservlet;

import com.graphbuilder.math.func.FactFunction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import zqdb.O_DOFIVE;
import zqdb.O_INFO;
import zqtools.DBUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

@WebServlet(name = "dofiveServlet", urlPatterns = "/dofive")
public class dofiveServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String ls_localsignature;
        String ls_signature;
        String ls_timestamp;
        JSONObject jret = new JSONObject();

        request.setCharacterEncoding("utf8");
        StringBuilder sbr = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sbr.append(line).append('\n');
            }
            if (sbr.length() > 1) {
                sbr.replace(sbr.length() - 1, sbr.length(), "");
            }
        } catch (IOException e) {
            System.out.println(("RequestUtil,IOException:" + e));
        }
        String str = sbr.toString();

        JSONObject jget = JSONObject.fromObject(str);
        ls_signature = jget.getString("signature");
        ls_timestamp = jget.getString("timestamp");

        try {
            ls_localsignature = f_MD5(cotants.dofiveAppid + ls_timestamp + cotants.dofiveAppkey);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //System.out.println(ls_localsignature);
        if (!ls_localsignature.equals(ls_signature)) {
            jret.put("code", "0");
            jret.put("msg", "无效签名信息");
            jret.put("data", new JSONArray());
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print(jret);
            jret.clear();
            return;
        }

        O_DOFIVE of = new O_DOFIVE();
        //只遍历key
        for (Object key : jget.keySet()) {
            if ("appid".equals(key)) {
                of.setAppid(jget.getString("appid"));
            } else if ("signature".equals(key)) {
                of.setSignature(jget.getString("signature"));
            } else if ("timestamp".equals(key)) {
                of.setTimestamp(jget.getString("timestamp"));
            } else if ("concmd".equals(key)) {
                of.setConcmd(jget.getString("concmd"));
            } else if ("countid".equals(key)) {
                of.setCountid(jget.getString("countid"));
            } else if ("consume".equals(key)) {
                of.setConsume(jget.getString("consume"));
            } else if ("consumexxx".equals(key)) {          //--处理异常后的额外单独处理，临时添加
                of.setConsume(jget.getString("consumexxx"));
            }else if ("type".equals(key)) {
                of.setType(jget.getString("type"));
            } else if ("online".equals(key)) {
                of.setOnline(jget.getString("online"));
            } else if ("datetime".equals(key)) {
                of.setDatetime(jget.getString("datetime"));
            } else if ("uuid".equals(key)) {
                of.setUuid(jget.getString("uuid"));
            } else if ("cardno".equals(key)) {
                of.setCardno(jget.getString("cardno"));
            } else if ("begindate".equals(key)) {
                of.setBegindate(jget.getString("begindate"));
            } else if ("enddate".equals(key)) {
                of.setEnddate(jget.getString("enddate"));
            } else if ("reccount".equals(key)) {
                of.setReccount(jget.getString("reccount"));
            } else if ("sum".equals(key)) {
                of.setSum(jget.getString("sum"));
            }else if ("dosite".equals(key)) {
                of.setDosite(jget.getString("dosite"));
            }else if ("recid".equals(key)) {
                of.setRecid(jget.getString("recid"));
            }
        }

        JSONObject j = DBUtil.f_dofive(of);

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print(j);
        j.clear();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request, response);
    }

    public static Map<Object, Object> jsonToMap(Object jsonObj) {
        JSONObject jsonObject = JSONObject.fromObject(jsonObj);
        return (Map<Object, Object>) (Map) jsonObject;
    }

    public static String f_MD5(String data) throws Exception {
        java.security.MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
        }
        return sb.toString();
    }
}
